// https://leetcode.cn/problems/recover-binary-search-tree/submissions/

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

// 整个值序列中不满足条件的位置或者有两个（不相邻），或者有一个（相邻）。可以根据中序遍历是否从小到大来判断。
// 迭代
class Solution {
public:
    void recoverTree(TreeNode* root) {
        stack<TreeNode*> s;
        TreeNode* pre = NULL;
        TreeNode* rec1 = NULL;
        TreeNode* rec2 = NULL;
        while(root || !s.empty()) {
            while (root) {
                s.push(root);
                root = root->left;
            }
            root = s.top();
            s.pop();
            if (pre && pre->val > root->val) {
                rec2 = root;
                if (!rec1) rec1 = pre;
                else break;
            }
            pre = root;
            root = root->right;
        }
        swap(rec1->val, rec2->val);
    }
};

class Solution {
public:
    TreeNode* rec1 = NULL;
    TreeNode* rec2 = NULL;
    TreeNode* pre = NULL;
    void traverse(TreeNode* root) {
        if (!root) return;
        traverse(root->left);
        if (pre && pre->val > root->val) {
            rec2 = root;
            if (!rec1) rec1 = pre;
            else return;
        } 
        pre = root;
        traverse(root->right);
    }
    void recoverTree(TreeNode* root) {
        traverse(root);
        swap(rec1->val, rec2->val);
    }
};